package com.asiainfo.ncrm;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Routon.iDRCtLib.Des3;
import com.asiainfo.ncrm.common.Constant;
import com.asiainfo.ncrm.common.SharedPreferencesUtils;
import com.asiainfo.ncrm.nfc.IdCard_Bean;
import com.invs.BtReaderClient;
import com.invs.DeviceInfo;
import com.invs.IClientCallBack;
import com.invs.InvsIdCard;
import com.sdses.Util;
//import com.sdses.Util;
import com.yast.yadrly001.BtReaderClient.People;

public class ListActivity extends Activity {
	// 调试
	private static final String TAG = "DeviceListActivity";
	private static final boolean D = true;
	// 返回别的意图
	public static String EXTRA_DEVICE_ADDRESS = "device_address";
	// 适配器
	private BluetoothAdapter mBtAdapter;
	private ArrayAdapter<String> mPairedDevicesArrayAdapter;
	private ArrayAdapter<String> mNewDevicesArrayAdapter;
	private Context mContext;
	private String mStrTDESPassword;
	private SharedPreferencesUtils preferencesUtils=null;
	private Set<DeviceInfo> devices=null;
	
	private com.invs.BtReaderClient mClientInvs = null;// 因纳伟盛
	private com.yast.yadrly001.BtReaderClient mClientYast = null;// 银安科技
	private com.Routon.iDRCtLib.BtReaderClient mClientIDRCtL=null;//精伦科技
	private com.sdses.BtReaderClient mClientSdse=null;//神思电子

	@SuppressWarnings("unchecked")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		
		setContentView(R.layout.list);
		Button scanButton = (Button) findViewById(R.id.button_scan);
		scanButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				doDiscovery();
				// v.setVisibility(View.GONE);
			}
		});
		Button clearButton = (Button) findViewById(R.id.butclearbluetooth);
		clearButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				clearbluetoothlist();
			}
		});
		// 初始化数组适配器。一个已配对装置和
		// 获取本地蓝牙适配器
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();
		if(!mBtAdapter.isEnabled()){
			mBtAdapter.enable();
		}
		// 一个新发现的设备
		mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.device_name);
		mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.device_name);

		// 寻找和建立配对设备列表
		ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
		pairedListView.setAdapter(mPairedDevicesArrayAdapter);
		pairedListView.setOnItemClickListener(mDeviceClickListener);

		// 寻找和建立为新发现的设备列表
		ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
		newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
		newDevicesListView.setOnItemClickListener(mDeviceClickListener);

		// 注册时发送广播给设备
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

		// 广播时发现已完成注册
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, filter);

		// 得到一套目前配对设备
		preferencesUtils=new SharedPreferencesUtils(mContext, "BondedBtDevice");
		devices=preferencesUtils.getObject("devices", Set.class);
		Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

		// If there are paired devices, add each one to the ArrayAdapter
		if(devices==null){
			devices = new HashSet<DeviceInfo>();
		}
		for (BluetoothDevice device : pairedDevices){
			DeviceInfo deviceInfo=new DeviceInfo();
			deviceInfo.setAddress(device.getAddress());
			deviceInfo.setName(device.getName());
			saveDevices(deviceInfo);
			devices=preferencesUtils.getObject("devices", Set.class);
		}
		if (devices.size() > 0) {
			findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
			for (DeviceInfo device : devices) {
				mPairedDevicesArrayAdapter.add(device.getName() + "\n"
						+ device.getAddress());
			}
		} else {
			String noDevices = getResources().getText(R.string.none_paired)
					.toString();
			mPairedDevicesArrayAdapter.add(noDevices);
		}
		initBtScan();
		Toast.makeText(mContext,"拍照功能已关闭，请使用蓝牙二代身份证识别设备读取身份证信息！",Toast.LENGTH_LONG).show();
	}

	private void initBtScan() {
		mClientInvs = new BtReaderClient(mContext);
		mClientInvs.setCallBack(new IClientCallBack() {

			@Override
			public void onBtState(boolean arg0) {
				if (arg0) {
					Toast.makeText(mContext,
							"蓝牙设备连接成功,正在读取身份证信息...",
							Toast.LENGTH_SHORT).show();
					InvsIdCard card = mClientInvs.readCard();
					mClientInvs.disconnectBt();
					Intent intent = new Intent();
					if (card == null || card.getName() == null) {
						Toast.makeText(mContext,
								"扫描仪未检测到身份证，请重新放置身份证到扫描仪上！",Toast.LENGTH_SHORT).show();
					} else {

						
						Bundle bundle = new Bundle();
						Map<String,Object> temp = new HashMap<String, Object>();
						
						temp.put("partyName", card.getName());
						temp.put("certNumber", card.getIdNo());
						temp.put("certAddress", card.getAddress());
						temp.put("bornDay", card.getBirth());
//						temp.put("identityPic", card.get);
						temp.put("nation", card.getNation());
						temp.put("gender", card.getSex());
						JSONObject json = new JSONObject(temp);
						bundle.putString("result", json.toString());
						intent.putExtras(bundle);
						
						
						setResult(RESULT_OK, intent);
						finish();
					}
				}
			}
		});
		mClientYast = new com.yast.yadrly001.BtReaderClient(mContext);
		mClientYast.setCallBack(new com.yast.yadrly001.IClientCallBack() {

					@Override
					public void onBtState(boolean arg0) {
						if (arg0) {
							Toast.makeText(mContext,
									"蓝牙设备连接成功,正在读取身份证信息...",
									Toast.LENGTH_SHORT).show();
							People people = mClientYast.read();
							mClientYast.disconnectBt();
							Intent intent = new Intent();
							if (people == null
									|| people.getPeopleName() == null) {
								Toast.makeText(mContext,
										"扫描仪未检测到身份证，请重新放置身份证到扫描仪上！",Toast.LENGTH_SHORT).show();
							} else {

								Bundle bundle = new Bundle();
								Map<String,Object> temp = new HashMap<String, Object>();
								
								temp.put("partyName", people.getPeopleName());
								temp.put("certNumber", people.getPeopleIDCode());
								temp.put("certAddress", people.getPeopleAddress());
								temp.put("bornDay", people.getPeopleBirthday());
								temp.put("identityPic", people.getPhoto());
								temp.put("nation", people.getPeopleNation());
								temp.put("gender", people.getPeopleSex());
								JSONObject json = new JSONObject(temp);
								bundle.putString("result", json.toString());
								intent.putExtras(bundle);
								
								setResult(RESULT_OK, intent);
								finish();
							}
						}
					}
				});
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        mStrTDESPassword = sp.getString("passwordPref", "31323334353637383132333435363738");
		mClientIDRCtL=new com.Routon.iDRCtLib.BtReaderClient(mContext);
		mClientIDRCtL.setCallBack(new com.Routon.iDRCtLib.IClientCallBack() {

			@SuppressLint("NewApi")
			@Override
			public void onBtState(boolean arg0) {
				if (arg0) {
					Toast.makeText(mContext,
							"蓝牙设备连接成功,正在读取身份证信息...",
							Toast.LENGTH_SHORT).show();
					Map<String, Object> idCardInfo = mClientIDRCtL.readCert();
					mClientIDRCtL.disconnectBt();
					int ret = (Integer) idCardInfo.get("resultFlag");
					InvsIdCard card=null;
					if (ret == 0)
					{
						String content = (String) idCardInfo.get("resultContent");
						byte[] key = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38};
						byte[] iv = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
						byte[] cryto = Base64.decode(content, Base64.NO_WRAP);
						str2hex(mStrTDESPassword, key);
						try {
							byte[] plain = Des3.des3DecodeCBC(key, iv, cryto);
							card=parseCardInfo(plain);
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
					Intent intent = new Intent();
					if (card == null || card.getName() == null) {
						Toast.makeText(mContext,
								"扫描仪未检测到身份证，请重新放置身份证到扫描仪上！",Toast.LENGTH_SHORT).show();
					} else {
//						intent.putExtra("NAME", card.getName());
//						intent.putExtra("SEX", card.getSex());
//						intent.putExtra("BIRTHDAY", card.getBirth());
//						intent.putExtra("NATION", card.getNation());
//						intent.putExtra("ADDRESS",
//								card.getAddress());
//						intent.putExtra("NUM", card.getIdNo());
//						intent.putExtra("TYPE", 1);
						Bundle bundle = new Bundle();
						Map<String,Object> temp = new HashMap<String, Object>();
						
						temp.put("partyName", card.getName());
						temp.put("certNumber", card.getIdNo());
						temp.put("certAddress", card.getAddress());
						temp.put("bornDay", card.getBirth());
//						temp.put("identityPic", card.get);
						temp.put("nation", card.getNation());
						temp.put("gender", card.getSex());
						JSONObject json = new JSONObject(temp);
						bundle.putString("result", json.toString());
						intent.putExtras(bundle);
						setResult(RESULT_OK, intent);
						finish();
					}
				}
			}
		});
			
	}

	private InvsIdCard parseCardInfo(byte[] msg) {
		InvsIdCard cardInfo = null;
		String str = new String(msg);
		Log.i(TAG, str);
		
		//add wanghong
		ByteArrayInputStream inputStream = new ByteArrayInputStream(msg);
		XmlPullParser xmlParser = Xml.newPullParser();  
		try {
			xmlParser.setInput(inputStream, "UTF-8");
			
			int type;
			
			try {
				while((type = xmlParser.next()) != XmlPullParser.END_TAG && type != XmlPullParser.END_DOCUMENT) {
					
					if (type != XmlPullParser.START_TAG) {
	                    continue;
	                }
					
					String sTag = xmlParser.getName();//获取节点　
					String TAG_NAME="certificate";
					cardInfo=new InvsIdCard();
					if(TAG_NAME.equalsIgnoreCase(sTag))
					{
						while((type = xmlParser.next()) != XmlPullParser.END_TAG && type != XmlPullParser.END_DOCUMENT) {
							if (type != XmlPullParser.START_TAG) {
			                    continue;
			                }
							String sTagsub = xmlParser.getName();//获取节点
							if("partyName".equalsIgnoreCase(sTagsub))
							{
								cardInfo.setName(xmlParser.nextText());//获取节点值　
							}
							if("gender".equalsIgnoreCase(sTagsub))
							{
							  String strGender = xmlParser.nextText();
							  if (strGender.equals("1"))
								  cardInfo.sex = "男";
							  else
								  cardInfo.sex = "女";
							}
							if("nation".equalsIgnoreCase(sTagsub))
							{
								cardInfo.nation= xmlParser.nextText();
							}
							if("bornDay".equalsIgnoreCase(sTagsub))
							{
								cardInfo.birth= xmlParser.nextText();
							}
							if("certAddress".equalsIgnoreCase(sTagsub))
							{
								cardInfo.address= xmlParser.nextText();
							}
							if("certNumber".equalsIgnoreCase(sTagsub))
							{
								cardInfo.idNo= xmlParser.nextText();
							}
							if("certOrg".equalsIgnoreCase(sTagsub))
							{
								cardInfo.police= xmlParser.nextText();
							}
							if("effDate".equalsIgnoreCase(sTagsub))
							{
								cardInfo.end= xmlParser.nextText();
							}
							if("expDate".equalsIgnoreCase(sTagsub))
							{
								cardInfo.start= xmlParser.nextText();
							}
						}								
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cardInfo;
	}
	private void str2hex(String str, byte[] output) {
		int len = str.length() / 2;
		for (int i = 0; i < len; i++) {
			output[i] = (byte)(0xff & Integer.parseInt(str.substring(i*2,i*2+2),16));
		}
	}
	
	private void unpairDevice() {
		try {
			Set<BluetoothDevice> pairedDevices=mBtAdapter.getBondedDevices();
			for (BluetoothDevice device : pairedDevices){
				Method m = device.getClass()
						.getMethod("removeBond", (Class[]) null);
				m.invoke(device, (Object[]) null);
			}
		} catch (Exception e) {
			// Log.e(TAG, e.getMessage());
		}
	}

	private void clearbluetoothlist() {
		if (devices.size() > 0) {
			mPairedDevicesArrayAdapter.clear();
			mPairedDevicesArrayAdapter.notifyDataSetChanged();
			unpairDevice();
			findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
			devices.clear();
			preferencesUtils.setObject("devices", devices);
			Toast.makeText(this, "清除配对列表成功", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, "没有配对过的设备", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 确保我们没有发现了
		if (mBtAdapter != null) {
			mBtAdapter.cancelDiscovery();
		}
		// 注销广播听众
		unregisterReceiver(mReceiver);
	}

	/**
	 * 发现与bluetoothadapter启动装置
	 */
	private void doDiscovery() {
		if (D)
			Log.d(TAG, "doDiscovery()");

		// 显示扫描的称号
		setProgressBarIndeterminateVisibility(true);
		setTitle(R.string.scanning);

		// 打开新设备的字幕
		findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

		// 如果我们已经发现，阻止它
		if (mBtAdapter.isDiscovering()) {
			mBtAdapter.cancelDiscovery();
		}

		// 要求从bluetoothadapter发现
		mBtAdapter.startDiscovery();
	}

	// 点击听众的所有设备在listviews
	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
			// 因为它是浪费的，取消发现我们的连接
			mBtAdapter.cancelDiscovery();

			// 获得设备地址，这是近17字的
			// 视图
			String info = ((TextView) v).getText().toString();
			if("没有建立连接".equals(info)){
				return;
			}
			String name = info.substring(0, info.length() - 17);
			String address = info.substring(info.length() - 17);
			DeviceInfo btDev = new DeviceInfo();
			btDev.setAddress(address);
			btDev.setName(name);
			try {
				if (name != null){
					if(name.startsWith(Constant.INVS_NAME)) {
						if(!mClientInvs.connectBt(address)){
							Toast.makeText(mContext, "蓝牙扫描设备连接失败，请确认所选择设备是否正确！...",
									Toast.LENGTH_SHORT).show();
						}else {
							saveDevices(btDev);
						}
					}else if(name.startsWith(Constant.YAST_NAME)) {
						if(!mClientYast.connectBt(address)){
							Toast.makeText(mContext, "蓝牙扫描设备连接失败，请确认所选择设备是否正确！...",
									Toast.LENGTH_SHORT).show();
						}else {
							saveDevices(btDev);
						}
					}else if(name.startsWith(Constant.IDR_NAME)) {
						if(!mClientIDRCtL.connectBt(address)){
							Toast.makeText(mContext, "蓝牙扫描设备连接失败，请确认所选择设备是否正确！...",
									Toast.LENGTH_SHORT).show();
						}else {
							saveDevices(btDev);
						}
					}else if (name.startsWith(Constant.SDSE_NAME)) {
						mClientSdse=new com.sdses.BtReaderClient(ListActivity.this);
						mClientSdse.setCallBack(new com.sdses.IClientCallBack(){

							@SuppressLint("NewApi")
							@Override
							public void onBtState(boolean arg0) {
								if (arg0) {
									Toast.makeText(mContext,
											"蓝牙设备连接成功,正在读取身份证信息...",
											Toast.LENGTH_SHORT).show();
									HashMap<String,Object> cardInfo = mClientSdse.readCert();
									mClientSdse.disconnectBt();
									mClientSdse.Destroy();
									InvsIdCard card=null;
									int resultFlag=Integer.parseInt(String.valueOf(cardInfo.get("resultFlag")));
									if(resultFlag==0){
										String content = (String) cardInfo.get("resultContent");
										if((content!=null)&&(content.length()>0)){
									       	byte[] str4 = null;
											   byte[] id2EncryptStr=Base64.decode(content.getBytes(),Base64.DEFAULT);
									             //   	        Log.w("ComShell","In PullParseTotalInfoXML id2EncryptStr is:"+ Util.toHexStringNoSpace(id2EncryptStr,  id2EncryptStr.length));//Integer.parseInt(xmlPullParser.nextText()));
									                            
									           byte[] key = new byte[32];
									           String tKey =  "1EAA86638D60E1951EC51581F3AF3A15";
									                      
									           
									           String tmpKey = tKey.substring(0, 16);
									           tKey = tKey + tmpKey;
									           key = Util.hexStringToBytes(tKey);
									           try {
									        	   byte[] keyiv = {0, 1, 2, 3, 4, 5, 6, 7};
									        	   str4 = Des3.des3DecodeCBC(key,keyiv,id2EncryptStr);
									           } catch (Exception e) {
									        	   e.printStackTrace();
									           }
									           card=parseCardInfo(str4);
									           Intent intent = new Intent();
									           if (card == null || card.getName() == null) {
									        	   Toast.makeText(mContext,
									        			   "扫描仪未检测到身份证，请重新放置身份证到扫描仪上！",Toast.LENGTH_SHORT).show();
									           } else {
									        	   intent.putExtra("NAME", card.getName());
									        	   intent.putExtra("SEX", card.getSex());
									        	   intent.putExtra("BIRTHDAY", card.getBirth());
									        	   intent.putExtra("NATION", card.getNation());
									        	   intent.putExtra("ADDRESS",
									        			   card.getAddress());
									        	   intent.putExtra("NUM", card.getIdNo());
									        	   intent.putExtra("TYPE", 1);
									        	   setResult(1, intent);
									        	   finish();
									           }
									}else {
										Toast.makeText(mContext,String.valueOf(cardInfo.get("msg"))
												,Toast.LENGTH_SHORT).show();
										
									}
								}
							}
							}
						});
						if(!mClientSdse.connectBt(address)){
							mClientSdse.Destroy();
							Toast.makeText(mContext, "蓝牙扫描设备连接失败，请确认所选择设备是否正确！...",
									Toast.LENGTH_SHORT).show();
						}else {
							saveDevices(btDev);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 传蓝牙地址给主界面
			// 结果，完成这项活动
		}
	};
	String[] adress = new String[500];
	int counts = 0;
	boolean add = true;
	// 该broadcastreceiver监听设备和
	// 变化的标题时，发现完成
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@SuppressLint("DefaultLocale")
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 当发现设备
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// 把蓝牙设备对象的意图
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				//过滤多余设备
				String name=device.getName();
				if (!(name != null && (name.startsWith(Constant.IDR_NAME) || name.startsWith(Constant.INVS_NAME) || name.startsWith(Constant.YAST_NAME)|| name.startsWith(Constant.SDSE_NAME)))){
					return;
				}
				// 如果它已经配对，跳过它
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {

					add = true;

					for (int i = 0; i < counts; i++) {
						if (device.getAddress().trim().toUpperCase()
								.equals(adress[i])) {
							add = false;
						}
					}
					if (add == true) {

						adress[counts] = device.getAddress().trim()
								.toUpperCase();
						mNewDevicesArrayAdapter.add(device.getName() + "\n"
								+ device.getAddress());
						counts = counts + 1;

					}

				}

				// 当发现后，改变活动名称
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				setProgressBarIndeterminateVisibility(false);
				setTitle(R.string.select_device);
				if (mNewDevicesArrayAdapter.getCount() == 0) {
					String noDevices = getResources().getText(
							R.string.none_found).toString();
					mNewDevicesArrayAdapter.add(noDevices);
				}
			}
		}
	};
	/**
	 * 保存已配对的蓝牙设备信息到已配对列表，方便下次连接
	 * @param device
	 */
	public void saveDevices(DeviceInfo device) {
		if(devices.size() < 1){
			devices.add(device);
			preferencesUtils.setObject("devices", devices);
		}
		boolean flag = true;
		for (DeviceInfo deviceInfo : devices) {
			if (deviceInfo.getAddress() != null && deviceInfo.getAddress()
					.equals(device.getAddress())) {
				flag = false;
			}
		}
		if(flag){
			devices.add(device);
			preferencesUtils.setObject("devices", devices);
		}
	}
}
